package cn.wolfcode.advice;

import cn.wolfcode.exception.LogicException;
import cn.wolfcode.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 统一异常处理:这样做的好处是不用再单个捕获异常了
 * @Author: 伍家钰
 * @Date: 2020/8/8 20:00
 * @Version: 1.0
 */
@ControllerAdvice
public class CommonExceptionHandler {
    /**
     * 处理自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public Object handlerLogic(Exception e, HttpServletResponse resp) {
        e.printStackTrace();
        resp.setContentType("application/json;charset:utf-8");
        return new JsonResult<>(JsonResult.CODE_ERROR_PARAM, e.getMessage(), null);
    }

    /**
     * 处理运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Object handlerRuntimeException(Exception e, HttpServletResponse resp) {
        e.printStackTrace();
        resp.setContentType("application/json;charset:utf-8");
        return new JsonResult<>(JsonResult.CODE_ERROR, "RuntimeException:系统错误,请联系管理员", null);
    }

    /**
     * 处理非运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handlerException(Exception e, HttpServletResponse resp) {
        e.printStackTrace();
        resp.setContentType("application/json:charset:utf-8");
        return new JsonResult<>(JsonResult.CODE_ERROR, "Exception:系统错误,请联系管理员", null);
    }
}
